package com.service.ai;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@Service
public class AiChatService {

    private static final Logger logger = LoggerFactory.getLogger(AiChatService.class);

    // 七牛云 Claude 代理地址
    @Value("${ai.qiniu-claude.url:https://openai.qiniu.com/v1/chat/completions}")
    private String apiUrl;

    // 七牛云大模型 API Key
    @Value("${ai.qiniu-claude.key:}")
    private String apiKey;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ObjectMapper objectMapper;


    public String generateReply(String userMessage, List<Map<String, String>> historyMessages) {
        if (!StringUtils.hasText(userMessage)) {
            return "请输入您的问题。";
        }

        try {
            // 构建消息（含 system prompt）
            List<Map<String, String>> messages = new ArrayList<>();

            // system 消息
            Map<String, String> systemMsg = new HashMap<>();
            systemMsg.put("role", "system");
            systemMsg.put("content", "你是一位专业的心理咨询师，请用温暖、简洁、有同理心的中文回答用户的问题，不要超过1000字。");
            messages.add(systemMsg);

            // 添加历史对话（可选，可能为空）
            if (historyMessages != null) {
                messages.addAll(historyMessages);
            }

            // user 消息
            Map<String, String> userMsg = new HashMap<>();
            userMsg.put("role", "user");
            userMsg.put("content", userMessage);
            messages.add(userMsg);

            // 1. 构建请求体（OpenAI 格式）
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "deepseek-v3?search"); // 七牛云支持的模型名
            requestBody.put("messages", messages);
            requestBody.put("max_tokens", 1000);
            requestBody.put("temperature", 0.7);

            // 2. 打印请求体
            String jsonRequestBody = objectMapper.writeValueAsString(requestBody);
            logger.info("【七牛云 Claude 请求】URL: {}", apiUrl);
            logger.info("【请求体】\n{}", jsonRequestBody);

            // 3. 设置 Header（七牛云支持 Bearer）
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            if (StringUtils.hasText(apiKey)) {
                headers.setBearerAuth(apiKey); // 七牛云支持此方式
            } else {
                logger.warn("七牛云 AI API Key 未配置！");
            }

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

            // 4. 发送请求
            ResponseEntity<Map> response = restTemplate.exchange(
                    apiUrl,
                    HttpMethod.POST,
                    entity,
                    Map.class
            );

            // 5. 打印响应
            Map<String, Object> responseBody = response.getBody();
            if (responseBody != null) {
                String jsonResponse = objectMapper.writeValueAsString(responseBody);
                logger.info("【七牛云 Claude 响应】状态码: {}", response.getStatusCode());
                logger.info("【响应体】\n{}", jsonResponse);
            }

            // 6. 解析 OpenAI 格式响应
//            if (responseBody != null && responseBody.containsKey("choices")) {
//                List<Map<String, Object>> choices = (List<Map<String, Object>>) responseBody.get("choices");
//                if (!choices.isEmpty()) {
//                    Map<String, Object> message = (Map<String, Object>) choices.get(0).get("message");
//                    String reply = (String) message.get("content");
//                    return reply != null ? reply.trim() : "AI 未返回有效内容。";
//                }
//            }
            if (responseBody != null && responseBody.containsKey("choices")) {
                List<Map<String, Object>> choices = (List<Map<String, Object>>) responseBody.get("choices");
                if (!choices.isEmpty()) {
                    Map<String, Object> message = (Map<String, Object>) choices.get(0).get("message");
                    String reply = (String) message.get("content");
                    if (reply != null) {
                        // 只去除换行符和制表符，保留空格
                        reply = reply.replaceAll("[\\r\\n\\t]", "").trim();
                        return reply;
                    } else {
                        return "AI 未返回有效内容。";
                    }
                }
            }

            return "抱歉，AI 暂时无法回答。";

        } catch (Exception e) {
            logger.error("调用七牛云 Claude API 异常", e);
            return "很抱歉，AI 服务暂时不可用，请稍后再试。";
        }
    }
}
